//app.js
var http = require('./utils/httpHelper.js'), code_type = 0, inviter_id = 0, need_redirect = false, scene = 0;
var config = require('./config.js')
App({
  onLaunch: function (options) {
    scene = options.scene;
    //来自用户直接分享商品的链接
    if (!this.check_empty(options.query.inviter_id)) {
      inviter_id = options.query.inviter_id;
    }
    this.onShow()
  },
  onShow: function () {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    var res = wx.getStorageInfoSync()
    if (!rd_session) {
      wx.clearStorageSync();
      self.login(code_type, inviter_id, scene);
    } else {
      wx.checkSession({
        success: function () {
          self.check_rdsession();
        },
        fail: function () {
          //登录态过期
          self.login(code_type, inviter_id, scene);
        }
      })
    }
  },
  //code_type：扫码类型；inviter_id：邀请者id；scene：入口场景
  login: function (code_type, inviter_id, scene) {
    var self = this;
    console.log("login..")
    wx.login({
      success: function (res) {
        console.log("wxloginsuccess")
        if (res.code) {
          var code = res.code;
          wx.getUserInfo({
            success: function (res) {
              console.log("success")
              var rawData = res['rawData'];
              var signature = res['signature'];
              var encryptData = res['encryptData'];
              var encryptedData = res['encryptedData'];
              var iv = res['iv'];
              //发起网络请求
              var data = {
                scene: scene,
                code_type: code_type,
                inviter_id: inviter_id,
                "mchid": 'd072f71878ca8a3288b05bb50c0ecc65',
                "code": code,
                "rawData": rawData,
                "signature": signature,
                "encryptData": encryptData,
                'iv': iv,
                'encryptedData': encryptedData
              }
              wx.request({
                url: config.HTTP_BASE_URL + 'wxlogin',
                method: 'POST',
                data: data,
                success: function (ress) {
                  if (ress.data.message === 'success') {
                    self.globalData.userInfo = ress.data;
                    self.globalData.hasLogin = true;
                    var openid = ress.data.openId;
                    wx.setStorageSync('openid', openid);
                    wx.setStorageSync('userinfo', ress.data);
                    //登录成功后做响应跳转
                    if (need_redirect) {
                      wx.navigateTo({
                        url: '/pages/goods/goods_detail_buy?id=' + good_id
                      })
                    }
                  } else {
                    wx.showModal({
                      title: '提醒',
                      content: '第三方登录失败！',
                    })
                  }
                }
              })
            },
            fail: function () {
              console.log("err")
              wx.showModal({
                title: '警告',
                content: '您点击了拒绝授权,将无法正常使用成纪先锋微平台，后期想要使用成纪先锋微平台，需在微信【发现】——【小程序】——删掉【成纪先锋微平台】，重新搜索授权登陆才可使用。',
              })
            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function (e) {
        console.log("wxloginfail")
      }
    });
  },
  check_rdsession: function () {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    self.ajax("/check_login", { rd_session: rd_session }, function (res) {
      if (res.message == 'offline') {
        wx.clearStorageSync();
        wx.removeStorageSync("rd_session");
        self.login();
      } else {
        self.globalData.hasLogin = true;
        self.globalData.userInfo = wx.getStorageSync('userinfo');
      }
    })
  },
  check_online: function () {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    if (!rd_session) {
      self.login();
    } else {
      wx.checkSession({
        success: function () {
          self.check_rdsession();
        },
        fail: function () {
          //登录态过期
          self.login();
        }
      })
    }
  },
  check_logined: function (para) {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    if (!rd_session) {
      typeof para.fail === 'function' && para.fail();
    } else {
      wx.checkSession({
        success: function () {
          self.ajax("check_login", { rd_session: rd_session }, function (res) {
            if (res.message == 'offline') {
              wx.clearStorageSync();
              wx.removeStorageSync("rd_session");
              typeof para.fail === 'function' && para.fail();
            } else {
              typeof para.success === 'function' && para.success();
            }
          })
        },
        fail: function () {
          typeof para.fail === 'function' && para.fail();
        }
      })
    }
  },
  checkUser(cb) {
    var rd_session = wx.getStorageSync('rd_session');
    http.httpPost("check_info", { rd_session: rd_session }, function (res) {
      console.log(res.data)
      typeof cb == "function" && cb(res.data, "");
    })
  },
  checkVip(cb) {
    var rd_session = wx.getStorageSync('rd_session');
    http.httpPost("check_vip", { rd_session: rd_session }, function (res) {
      console.log(res.data)
      typeof cb == "function" && cb(res.data, "");
    })
  },

  ajax(url, data, cb) {
    if (data == '') {
      data = {};
    }
    data.mchid = 'd072f71878ca8a3288b05bb50c0ecc65';
    wx.showNavigationBarLoading();
    wx.request({
      method: 'POST',
      url: config.HTTP_BASE_URL + url,
      data: data,
      success: (res) => {
        typeof cb == "function" && cb(res.data, "");
        // if(res.data.result == 'error'){
        //   wx.showModal({
        //     title: res.data.message,
        //     content: res.data.info,
        //   })
        // }
        wx.hideNavigationBarLoading();
      },
      fail: (err) => {
        typeof cb == "function" && cb(null, err.errMsg);
        wx.hideNavigationBarLoading();
      }
    });
  },
  buildpayparam: function (order_no, openid) {
    wx.request({
      url: config.BASE_URL + 'WePay/build_payparam',
      method: 'POST',
      // header: {
      //   'content-type': 'application/x-www-form-urlencoded'
      // },
      data: { order_no: order_no, openid: openid },
      success: function (res) {

        return res.data;
      },
    })


  },
  // 调用微信支付接口课程支付
  wxPayClass: function (para) {
    var _this = this;
    wx.request({
      url: config.BASE_URL + 'Api/build_class_payparam',
      method: 'POST',
      data: {
        order_no: para.order_no, openid: para.openid, mchid: 'd072f71878ca8a3288b05bb50c0ecc65',
        rd_session: wx.getStorageSync('rd_session')
      },
      success: function (res) {
        var param = res.data;
        console.log(param);
        wx.requestPayment({
          'timeStamp': param.timeStamp,
          'nonceStr': param.nonceStr,
          'package': param.package,
          'signType': 'MD5',
          'paySign': param.paySign,
          success: function (res) {
            typeof para.success === 'function' && para.success();
          },
          fail: function (res) {
            typeof para.fail === 'function' && para.fail();
          }
        })
      },
    })
  },
  // 调用微信支付接口商品支付
  wxPayGood: function (para) {
    var _this = this;
    wx.request({
      url: config.BASE_URL + 'Api/build_payparam',
      method: 'POST',
      data: {
        order_no: para.order_no, openid: para.openid, mchid: 'd072f71878ca8a3288b05bb50c0ecc65',
        rd_session: wx.getStorageSync('rd_session')
      },
      success: function (res) {
        var param = res.data;
        console.log(param);
        wx.requestPayment({
          'timeStamp': param.timeStamp,
          'nonceStr': param.nonceStr,
          'package': param.package,
          'signType': 'MD5',
          'paySign': param.paySign,
          success: function (res) {
            typeof para.success === 'function' && para.success();
          },
          fail: function (res) {
            typeof para.fail === 'function' && para.fail();
          }
        })
      },
    })
  },
  //直接调支付
  wxPays(para) {
    let param = para.data
    wx.requestPayment({
      'timeStamp': param.timeStamp,
      'nonceStr': param.nonceStr,
      'package': param.package,
      'signType': 'MD5',
      'paySign': param.paySign,
      success: function (res) {
        typeof para.success === 'function' && para.success();
      },
      fail: function (res) {
        typeof para.fail === 'function' && para.fail();
      }
    })
  },
  wxPaySuccess: function (param) {
    var orderId = param.orderId,
      goodsType = param.goodsType,
      formId = param.package.substr(10),
      t_num = goodsType == 1 ? 'AT0104' : 'AT0009';
    //发送模板消息通知
    //支付成功 跳转上一页
    wx.navigateBack({
      delta: 1
    })
  },

  wxPayFail: function (param, errMsg) {
    var orderId = param.orderId,
      formId = param.package.substr(10);

    //发送模板消息

  },
  check_empty: function (v) {
    switch (typeof v) {
      case 'undefined':
        return true;
      case 'string':
        if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
        break;
      case 'boolean':
        if (!v) return true;
        break;
      case 'number':
        if (0 === v || isNaN(v)) return true;
        break;
      case 'object':
        if (null === v || v.length === 0) return true;
        for (var i in v) {
          return false;
        }
      default:
        return true;
    }
    return false;
  },
  //检查手机号 是返回true
  checkPhone(phone) {
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      return false;
    } else {
      return true;
    }
  },
  sendTemplate: function (formId, templateData, success, fail) {
    var app = getApp();
    this.getJSON({
      url: '/WxAppApi/sendTemplate',
      data: {
        rd_session: app.rd_session,
        form_id: formId,
        data: templateData,
      },
      success: success,   // errorcode==0时发送成功
      fail: fail
    });
  },
  //自适应图片
  fixImgW(e, width) {
    var _this = this;
    var $width = e.detail.width,    //获取图片真实宽度  
      $height = e.detail.height,
      ratio = $width / $height;   //图片的真实宽高比例  
    var viewWidth = width,           //设置图片显示宽度，  
      viewHeight = width / ratio;    //计算的高度值
    return viewHeight
  },

  globalData: {
    appid: "",
    userInfo: ''
  }
})